/**
 * Created with JetBrains WebStorm.
 * User: geeth
 * Date: 10/25/12
 * Time: 4:58 PM
 * To change this template use File | Settings | File Templates.
 */

var JISU_JQ_SCRIPT_ID = 'jisu_jqueryScriptElementId';
var JISU_MAIN_SCRIPT_ID = 'jisu_mainScriptElementId';
var JISU_MAIN_ELEM_ID = 'jisu_mainHTMLElementId';
var JISU_MAIN_DOMAIN = 'www.jisushopping.com';
var JISU_MAIN_PROTOCOL = 'https:';
var JISU_SVC_URL = '//' + JISU_MAIN_DOMAIN + '/jisuweb';
var JISU_LOGINSVC_URL = 'https:'+'//' + JISU_MAIN_DOMAIN + '/jisuweb';
var JISU_MAIN_WEB_URL = '//' + JISU_MAIN_DOMAIN;
//var JISU_MAIN_SCRIPT_SRC = JISU_SVC_URL + '/js/cart/element.js?domain=' + document.domain;
var JISU_MAIN_SCRIPT_SRC = JISU_SVC_URL + '/js/cart/element.js?domain=' + window.location.host;
var JISU_COOKIECHK_SCRIPT_SRC = JISU_SVC_URL + '/js/cart/testcookie.js';
//var JISU_JQ_SCRIPT_SRC = JISU_MAIN_WEB_URL + '/js/lib/jquery.js';

var JISU_JQ_SCRIPT_SRC = 'https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js';
var jisuOtherImgArr = [];
var jisujQuery;


function jisu_initialize() {

   // if (window.location.host.indexOf(JISU_MAIN_DOMAIN) != -1) {
     //   alert("Not allowed from JiSu domain");
    var a = false;
    if (document.getElementsByTagName("body").length == 0) {
        var htmlElem = document.getElementsByTagName("html")[0];
        var headElem = document.getElementsByTagName("head")[0];
        var bodyElem = document.createElement("body");
        htmlElem.appendChild(bodyElem);
    }
    var framesVal = document.getElementsByTagName("frameset");
    var framesValLen = framesVal.length;
    for (var i = 0; i < framesValLen; i++) {
        framesVal[i].parentNode.removeChild(framesVal[i]);
    }
    jisu_linkCSS();
    jisuLoadJQ();
}


function jisu_loadJS(jsNodeId, jsNodeSrc, jsNodeCallback, addTime) {
    var jqScriptNode = document.getElementById(jsNodeId);
    if (jqScriptNode) {
        jqScriptNode.parentNode.removeChild(jqScriptNode);
    }
    jqScriptNode = document.createElement("script");
    jqScriptNode.type = "text/javascript";
    jqScriptNode.id = jsNodeId;
    jqScriptNode.src = jsNodeSrc + (addTime ? "?t=" + (new Date().getTime()) : "");
    //jqScriptNode.src = jsNodeSrc;


    if (jqScriptNode.readyState) {
        jqScriptNode.onreadystatechange = function () {
            if (this.readyState == "complete" || this.readyState == "loaded") {
                jsNodeCallback();
            }
        }
    } else {
        jqScriptNode.onload = jsNodeCallback
    }

    if (document.getElementsByTagName("head").length > 0) {
        document.getElementsByTagName("head")[0].appendChild(jqScriptNode)
    } else if (document.getElementsByTagName("body").length > 0) {
        document.getElementsByTagName("body")[0].appendChild(jqScriptNode)
    }
    //}
}

function jisuLoadJQ() {
    jisu_loadJS(JISU_JQ_SCRIPT_ID, JISU_JQ_SCRIPT_SRC, jisuLoadJQUI, false)
}

function jisuLoadJQUI() {
    jisu_loadJS("jisu_jqui", "https://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js", jisuCookieCheck, false)
}

function jisuCookieCheck() {
    jisu_loadJS("jisu_cookiechk", JISU_COOKIECHK_SCRIPT_SRC, jisuLoadElemJS, false)
}

function jisuLoadElemJS() {
    if (typeof  jisujQuery === "undefined") {
        jisujQuery = window.jQuery.noConflict(true);
    }
    jisu_loadJS(JISU_MAIN_SCRIPT_ID, JISU_MAIN_SCRIPT_SRC, new function () {
    }, true)
}


function jisu_createCookie(name, value, days) {
    var expires;
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    }
    else expires = "";
    document.cookie = name + "=" + value + expires + ";domain=www.jisushopping.com; path=/";
}

function jisu_readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function jisu_eraseCookie(name) {
    jisu_createCookie(name, "", -1);
}

function jisu_areCookiesEnabled() {
    var r = false;
    jisu_createCookie("testing", "Hello", 1);
    if (jisu_readCookie("testing") != null) {
        //console.log("Read cookie");
        r = true;
        jisu_eraseCookie("testing");
    }
    return r;
}


function jisu_createmainDiv() {



    //console.log("In main create jisuloggedInStatus="+jisuloggedInStatus);

    var mainElemNode = document.getElementById(JISU_MAIN_ELEM_ID);
    if (mainElemNode) {
        jisujQuery('#' + JISU_MAIN_ELEM_ID).draggable( 'disable' );
        jisu_removeChildNodes(mainElemNode);
        mainElemNode.parentNode.removeChild(mainElemNode);
    }
//    mainElemNode = document.createElement('div');

    var parntNode = document.createElement("div");
    parntNode.innerHTML = jisuCartElementHTML;
    document.body.appendChild(parntNode.firstChild);




    if (!jisuCookieCheck) {
        jisujQuery('#jisu_cartElemsId').hide();
        jisujQuery('#jisu_loginElemsDiv').hide();
        jisujQuery('#jisu_newCartDiv').hide();
        jisujQuery('#jisu_cookieMessageDiv').show();

        return;
    }
     else {
        jisujQuery('#jisu_cookieMessageDiv').hide();
     }


    jisujQuery('#' + JISU_MAIN_ELEM_ID).draggable( );


    if (!jisuloggedInStatus) {
        //console.log("Not loggedin");
        //jisujQuery('#jisu_loginElemsDiv').toggle();
        jisujQuery('#jisu_loginElemsDiv').show();
        jisujQuery('#jisu_cartElemsId').hide();
        jisujQuery('#jisu_newCartDiv').hide();
        return false;
    } else {
        jisujQuery('#jisu_loginElemsDiv').hide();
        jisujQuery('#jisu_cartElemsId').show();
        jisujQuery('#jisu_newCartDiv').hide();
        jisu_buildMainElems(mainElemNode);
    }




    //if (!jisuloggedInStatus) {
    //console.log('Not logged In');
    //  parntNode.innerHTML = jisuCartLoginHTML;
    //document.getElementsByTagName("body")[0].appendChild(mainElemNode);

    //return false;
    //} else {

    //console.log('Logged In');
    //}


    //  mainElemNode.setAttribute('id', JISU_MAIN_ELEM_ID)
    //mainElemNode.setAttribute('class', 'overlay_main_div');
    //maininElemNode.setAttribute('style', 'top:0px;left:0px;margin-left:0px;margin-top:0px;min-height:280px;width:430px;overflow: auto;background-color: #99CCFF; position: absolute;z-index:2147483646');
//    mainElemNode.setAttribute('style', 'z-index: 2147483646; top: 5px; right: 10px; opacity: 1;');


}

function jisu_buildMainElems() {

    //document.getElementsByTagName("body")[0].appendChild(theMainElemNode);

    jisu_GetCarts();
    //jisu_GetReasons();

    var docImages = document.getElementsByTagName('img'), docLen = docImages.length;
    var mainImgSrc, mainImgHeight = 0, mainImgWidth = 0;

    //jisujQuery('#jisu_mainHTMLElementId .jisu_greeting').text("Hello, "+jisuloggedInName);
    //jisujQuery('#jisu_mainHTMLElementId .jisu_greeting2').text("Hello, "+jisuloggedInName);
    jisujQuery('#jisu_mainHTMLElementId .jisu_greeting, #jisu_mainHTMLElementId .jisu_greeting2').html("Hello, "+jisuloggedInName);

    if (typeof jisuImgElementName !== "undefined") {
        //console.log(jisuImgElementName);
        var imgSelVals = jisuImgElementName.split(";");

        var imgi = 0;
        for (imgi = 0; imgi < imgSelVals.length; imgi++) {
            //console.log("Checking image sel=" + imgSelVals[imgi]);
            var imgSelVal = jisujQuery(imgSelVals[imgi]);
           // console.log("jq sel img=" + imgSelVal.html());

            if (typeof imgSelVal !== "undefined" && imgSelVal.is("img")) {
               // console.log("Val is image");
                mainImgSrc = imgSelVal.attr('src');
                mainImgWidth = imgSelVal.attr('width');
                mainImgHeight = imgSelVal.attr('height');
                break;
            }

        }
    }


    if (typeof mainImgSrc === "undefined") {
        for (var i = 0; i < docLen; i++) {
            if (!jisu_correctImage(docImages[i])) {
                continue;
            }


            if (docImages[i].width > mainImgWidth && docImages[i].height > mainImgHeight) {

                mainImgSrc = docImages[i].src;
                mainImgWidth = docImages[i].width;
                mainImgHeight = docImages[i].height;

            }

            try {
                jisuOtherImgArr.push(docImages[i]);
                /*
                 var newImg = document.createElement("img");
                 newImg.setAttribute('src', docImages[i].getAttribute("src"));
                 newImg.setAttribute('width', 80);
                 newImg.setAttribute('height', 80 * docImages[i].height / docImages[i].width);
                 newImg.setAttribute('onclick', 'jisu_changeItem(this)');
                 jisujQuery('#jisu_OtherImgDiv').append(newImg);
                 */
            } catch (err) {

                //console.log(err);
            }

            //newImg.setAttribute('style', 'float: left;top:30px;position: relative;');
        }
    }

    var mainImg = document.createElement("img");
    mainImg.setAttribute('src', mainImgSrc);

    if (Math.floor(138 * mainImgHeight / mainImgWidth) < 147) {

        mainImg.setAttribute('width', 138);
        mainImg.setAttribute('height', Math.floor(138 * mainImgHeight / mainImgWidth));

    } else {
        mainImg.setAttribute('height', 147);
        mainImg.setAttribute('width', Math.floor(mainImgWidth / mainImgHeight * 147));
    }



    jisujQuery('#jisuMainImg').append(mainImg);

    jisu_createOtherImgElem(0);

    var titleDesc = jisu_removeTags(document.title.toString());
    jisujQuery('#jisuMainTitle').val(titleDesc);
    jisujQuery('#jisuMainTitleInit').val(titleDesc);
    var priceResult = jisu_priceVal(jisuPriceElementName);
    jisujQuery('#jisuMainPrice').val(priceResult);
    jisujQuery('#jisuMainPriceInit').val(priceResult);

    var breadResult = jisu_breadVal(jisuBreadElementName);
    if (breadResult == null) {
        breadResult="";
    }
    jisujQuery('#jisuBreadcrumb').val(breadResult);

    //jisujQuery('#jisuMainLocation').attr('href', window.location.href);
    jisujQuery('#jisuMainLocation').val(window.location.href);


    jisujQuery('#jisuMainPrice').change(function() {
        jisu_changepricechk();
    });

    jisujQuery('#jisuMainPrice').keyup(function() {
        jisu_changepricechk();
    });



}

function jisu_changepricechk() {

    if (jisujQuery('#jisuMainPrice').val() == jisujQuery('#jisuMainPriceInit').val()) {
        jisujQuery('#jisu_pricedropchk').show();
        jisujQuery('#jisu_pricedropchk').prop('checked', true);
        jisujQuery('#jisu_pricedropchk_na').hide();
    }

    if (jisujQuery('#jisuMainPrice').val() != jisujQuery('#jisuMainPriceInit').val()) {
        jisujQuery('#jisu_pricedropchk').hide();
        jisujQuery('#jisu_pricedropchk').prop('checked', false);
        jisujQuery('#jisu_pricedropchk_na').show();

    }

}

function jisu_createOtherImgElem(startIndex) {
    var numItems = 2;
    var len = jisuOtherImgArr.length;
    //console.log("StartIndex="+startIndex+";Len="+len);

    var endIndex;
    if (len < numItems || startIndex + numItems >= len) {
        endIndex = len;
    } else {
        endIndex = startIndex + numItems
    }

     jisujQuery('#jisu_OtherImgDiv').empty();

    var newImg;
    if (startIndex > 0) {
        var nextInd = startIndex-1;
        newImg = document.createElement("img");
        newImg.setAttribute('src', JISU_MAIN_WEB_URL + "/images/blueArrowLeft_7x22.png");
        newImg.setAttribute('width', '7');
        newImg.setAttribute('height', '22');
        newImg.setAttribute('class', 'blueArrowLeft')
        newImg.setAttribute('onclick', 'jisu_createOtherImgElem('+nextInd+')');
        jisujQuery('#jisu_OtherImgDiv').append(newImg);
    }


    for (var i = startIndex; i < endIndex; i++) {
        try {

            newImg = document.createElement("img");
            newImg.setAttribute('src', jisuOtherImgArr[i].getAttribute("src"));
            newImg.setAttribute('width', 66);
            //newImg.setAttribute('height', 49);
            newImg.setAttribute('onclick', 'jisu_changeItem(this)');
            jisujQuery('#jisu_OtherImgDiv').append(newImg);

        } catch (err) {

           // console.log(err);
        }
    }

    if (startIndex + numItems < len - 1) {
        var nextInd = startIndex+1;
        newImg = document.createElement("img");
        newImg.setAttribute('src', JISU_MAIN_WEB_URL + "/images/blueArrowRight_7x22.png");
        newImg.setAttribute('width', '7');
        newImg.setAttribute('height', '22');
        newImg.setAttribute('class','blueArrowRight');
        newImg.setAttribute('onclick', 'jisu_createOtherImgElem('+nextInd+')');
        jisujQuery('#jisu_OtherImgDiv').append(newImg);
    }


}


function jisu_changeItem(item) {
    jisujQuery("#jisuMainAddCart").removeAttr("disabled");
    var theimage = jisujQuery('#jisuMainImg img');
    theimage.attr("src", item.src);

    if (Math.floor(138 * item.height / item.width) <147) {
    theimage.attr("height", Math.floor(138 * item.height / item.width));
    theimage.attr("width", 138);
    } else {
        theimage.attr("height", 147);
        theimage.attr("width", Math.floor(item.width/item.height * 147));
    }
    // jisujQuery('#jisuMainTitle').val('');
    // jisujQuery('#jisuMainTitleInit').val('');
    //jisujQuery('#jisuMainPrice').val('');
    //jisujQuery('#jisuMainPriceInit').val('');
}

function jisu_showNewCart() {
    jisujQuery('#jisu_cartElemsId').hide();
    jisujQuery('#jisu_newCartDiv').show();
}

function jisu_closeNewCart() {
    jisujQuery('#jisu_cartElemsId').show();
    jisujQuery('#jisu_newCartDiv').hide();
    return false;
}

function jisu_showCartSaved() {
    jisujQuery('#jisu_cartElemsId').hide();
    jisujQuery('#jisu_cartSavedDiv').show();
    var newAnimatingImage = jisujQuery('#jisuMainImg > img').clone();
    newAnimatingImage.css({'width': '60px','height': '60px'});
    newAnimatingImage.appendTo('#jisu_intoCart')
        .animate({
            left: 165,
            top: 117,
            textIndent: 60
        }, {
            step: function(go) {
                jisujQuery(this).css('-moz-transform','rotateZ('+go+'deg)');
                jisujQuery(this).css('-webkit-transform','rotateZ('+go+'deg)');
                jisujQuery(this).css('-o-transform','rotateZ('+go+'deg)');
                jisujQuery(this).css('transform','rotateZ('+go+'deg)');
            },
            duration: 1400,
            complete: function(){ /*alert('done')*/ }
        });

}



function jisu_GetReasons() {
    jisujQuery.ajax({
        headers: {
            Accept : "application/json",
            "Content-Type": "application/json"
        },
        accepts:"application/json, text/javascript, */*",
        url:JISU_SVC_URL + '/svc/cart/cartreason/all',
        dataType:"jsonp",
        success:function (data) {
            if (data.status == true) {
                var reasonResp = data.response;
                var len = reasonResp.length;
                var htmlStr = '';
                htmlStr += '<select id="jisuReasonNameSelect" name="jisuReasonNameSelect">';
                for (var i = 0; i < len; i++) {
                    htmlStr += '<option value="' + reasonResp[i].id + '">' + reasonResp[i].reasonName + '</option>'
                }
                htmlStr += '</select>';
                jisujQuery('#jisuCartReasons').append(htmlStr);

            } else {
                //console.log("Cat Get Failed!!! Response="
                //  + data.status);
                jisujQuery("#jisu_CartElemError").css("visibility", "visible");
            }
        },
        error:function (message) {
            //console.log("Cat Get Failed!!! Response="
            // + message);
            jisujQuery("#jisu_CartElemError").css("visibility", "visible");
        }
    });
}

function jisu_GetCarts() {
    jisujQuery.ajax({
        headers: {
            Accept : "application/json",
            "Content-Type": "application/json"
        },
        accepts:"application/json, text/javascript, */*",
        url:JISU_SVC_URL + "/svc/cart/cart/all",
        dataType:"jsonp",
        success:function (data) {
            if (data.status == true) {
                //console.log("Login Succeeded!!! Response="
                //  + data.status);

                var cartResp = data.response;
                var len = cartResp.length;
                var htmlStr = '';
                //if (len > 0) {
                    htmlStr += '<select id="jisuCartNameSelect" name="jisuCartNameSelect">';
                    htmlStr += '<option value="select">Select a cart</option>'
                    for (var i = 0; i < len; i++) {
                        htmlStr += '<option value="' + cartResp[i].id + '">' + cartResp[i].cartName + '</option>'
                    }
                    htmlStr += '</select>';
                    jisujQuery('#jisuMainCartNames').append(htmlStr);
               // } else {
               //     jisujQuery('#jisuMainCartNames').html('');
               // }

            } else {
                // console.log("Get Cart Failed!!! Response="
                //    + data.status);
                jisujQuery("#jisu_CartElemError").css("visibility", "visible");
            }
        },
        error:function (message) {
            // console.log("Get Cart Failed!!! Response="
            // + message);
            jisujQuery("#jisu_CartElemError").css("visibility", "visible");
        }
    });
}

function jisu_LoginUser() {
    jisujQuery.ajax({
        headers: {
            Accept : "application/json",
            "Content-Type": "application/json"
        },
        accepts:"application/json, text/javascript, */*",
        url:JISU_LOGINSVC_URL + "/svc/user/login",
        data:{"email":jisujQuery('#jisu_LoginEmail').val(), "password":jisujQuery('#jisu_loginPass').val(), "rememberme":jisujQuery('#jisu_login_signchbx').is(':checked')},
        dataType:"jsonp",
        success:function (data) {
            if (data.status == true) {
                //console.log("Login Succeeded!!! Response="
                //  + data.status);
                jisuloggedInStatus = true;
                jisuloggedInName = data.response.name;
                jisu_createmainDiv();
            } else {
                //console.log("Login Failed!!! Response="
                // + data.status);
                jisujQuery("#jisu_loginError").css("visibility", "visible");
            }
        },
        error:function (message) {
            //console.log("Login Failed!!! Response="
            //+ message);
            jisujQuery("#jisu_loginError").css("visibility", "visible");
        }
    });
}


function jisu_AddCart() {
    jisujQuery('#jisu_newCartChk').hide();
    var cartNm = jisujQuery('#jisu_newCartName').val();
    var cartChk = jisujQuery('#jisu_newCartChk').is(':checked');

    if (typeof cartNm === "undefined" || cartNm == null ) {
        jisujQuery('#jisu_newCartChk').text("Cart is required");
        jisujQuery('#jisu_newCartChk').show();
        return;
    }

    jisujQuery.ajax({
        headers: {
            Accept : "application/json",
            "Content-Type": "application/json"
        },
        accepts:"application/json, text/javascript, */*",
        url:JISU_SVC_URL + "/svc/cart/cart/save",
        data:{"name":cartNm, "isgift":cartChk},
        dataType:"jsonp",
        success:function (data) {
            if (data.status == true) {

                if (jisujQuery('#jisuMainCartNames').html() == '') {
                    var htmlStr = '';
                    htmlStr += '<select id="jisuCartNameSelect" name="jisuCartNameSelect">';
                    htmlStr += '<option value="select">Select cart</option>'
                    htmlStr += '<option selected="selected" value="'+data.response.id+'">'+data.response.cartName+'</option>';
                    jisujQuery('#jisuMainCartNames').html(htmlStr);
                } else {
                    jisujQuery('#jisuCartNameSelect').prepend('<option selected="selected" value="'+data.response.id+'">'+data.response.cartName+'</option>');
                }
                jisu_closeNewCart();
                //alert("Cart Added");



            } else {
                jisujQuery('#jisu_newCartChk').text("Cart save failed!");
                jisujQuery('#jisu_newCartChk').show();
            }
        },
        error:function (message) {
            jisujQuery('#jisu_newCartChk').text("Cart save failed!");
            jisujQuery('#jisu_newCartChk').show();
        }
    });
}

function jisu_removeChildNodes(someNode) {
    if (someNode.hasChildNodes()) {
        while (someNode.childNodes.length >= 1) {
            someNode.removeChild(someNode.firstChild);
        }
    }
}




function jisu_sendCartInfo() {
    var URL = JISU_SVC_URL + "/svc/cart/cartitem/save";
    var newCartReason, newCartName, mainimg, imgSrc, imgH, imgW, urlVal, desc, initDesc, initPrice, price, cartId, comment, isGift, chkPriceDrop, breadVal;

    desc = jisujQuery('#jisuMainTitle').val();
    initDesc = jisujQuery('#jisuMainTitleInit').val();
    urlVal = window.location.href;
    price = jisujQuery('#jisuMainPrice').val();
    initPrice = jisujQuery('#jisuMainPriceInit').val();
    breadVal = jisujQuery('#jisuBreadcrumb').val();

    cartId = jisujQuery('#jisuCartNameSelect').val();

    if (cartId == 'select') {
        alert('Please select a cart!');
        return;
    }

    newCartName = jisujQuery('#jisuNewCartName').val();
    newCartReason = jisujQuery('#jisuReasonNameSelect').val();
    comment = jisujQuery('#jisuMainComment').val();

    mainimg = jisujQuery('#jisuMainImg img');

    imgSrc = mainimg.attr('src');
    if (imgSrc != null && imgSrc.indexOf("http:") == -1 && imgSrc.indexOf("https:") == -1) {
        imgSrc = window.location.protocol + "//" + window.location.host + imgSrc;
    }


    imgW = mainimg.attr('width');
    imgH = mainimg.attr('height');

    isGift = jisujQuery('#jisuIsGift').is(':checked');

    chkPriceDrop = jisujQuery('#jisu_pricedropchk').is(':checked');
    //chkPriceDrop = false;

    jisujQuery("#jisuMainAddCart").attr("disabled", "disabled");
    if (typeof newCartName === "undefined") {
        newCartName="";
    }


    jisujQuery.ajax({
        headers: {
            Accept : "application/json",
            "Content-Type": "application/json"
        },
        accepts:"application/json, text/javascript, */*",
        url:URL,
        dataType:'jsonp',
        type:'GET',
        data:{"isgift":isGift, "url":urlVal, "imgsrc":imgSrc, "initDesc":initDesc, "desc":desc,
            "initPrice":initPrice, "price":price, "cartId":cartId, "imgW":imgW, "imgH":imgH,
            "newCartName":newCartName, "newCartReason":newCartReason, "retailer":jisuRetailerName, "comment":comment, "chkPriceDrop":chkPriceDrop, "bread":breadVal}
    }).success(function (resdata) {
            if (resdata.status == true) {
                var newLink = document.createElement("input");
                newLink.setAttribute('type', "button");
                newLink.setAttribute('value', "Go to Cart");
                newLink.setAttribute('onclick', "window.open('"+JISU_MAIN_WEB_URL
                    + "/index.html?cartId="+cartId+"')");
                //newLink.innerHTML = "Go to cart";

                jisujQuery('#jisu_cartSavedDiv').append(newLink);
                jisu_showCartSaved();
                //alert('Saved!');

                //jisujQuery('#jisuCartLink').toggle();
            }
        })
        .error(function () {
            // console.log("error");
        });


}

function jisu_Truncate(n) {
    return n | 0; // bitwise operators convert operands to 32-bit integers
}


function jisu_priceVal(priceElVal) {

    var priceElems = priceElVal;
    if (priceElems == null || priceElems === "undefined") {
        priceElems = '.price';
    }

    //console.log(priceElems);

    var priceVal = null;

    var priceElem = priceElems.split(";");
    //console.log(priceElem);

    var priceHtml = "";
    var i = 0;
    var result=null;
    for (i = 0; i < priceElem.length; i++) {

        priceHtml = jisujQuery(priceElem[i]).html();
        //console.log("PriceHTML="+priceHtml);
        result = jisu_priceFromText(priceHtml);

        // If Price is found, stop the loop
        if (result != null) {
            //console.log('Price HTML' + priceHtml);
            //console.log('Result='+result);
            break;
        }

    }

    return result;

}



function jisu_breadVal(breadElVal) {

    var breadElems = breadElVal;
    if (breadElems == null || breadElems === "undefined") {
        breadElems = '.breadcrumb';
    }
    var breadElem = breadElems.split(";");

    var i = 0;
    var result=null;
    for (i = 0; i < breadElem.length; i++) {

        result = jisujQuery(breadElem[i]).text();

        // If result is found, stop the loop
        if (result != null) {
            //console.log('Result='+result);
            break;
        }

    }

    return result;

}







function jisu_priceFromText(documentText) {

    var result = null;

    // documentText is set, look inside
    if (documentText != null) {
        //console.log('docText Init'+documentText);
        // Remove all inner HTML Code and whitespace
        documentText = documentText.replace(/<\/?[^>]+(>|$)/g, "");
        //console.log('docText Replace 1'+documentText);
        documentText = documentText.replace(/(\r\n|\n|\r|\t)/gm, "");
        //console.log('docText Replace 2:'+documentText);
        var regObj = new RegExp("[$]?(\\s|[ ]|&nbsp;)?[0-9]{1,3}((?:(,){0,1}[0-9]{3})*(?:\\.[0-9]{1,2})?)(?=\\D|[ ]|<|&nbsp;|$)", "g");
        if (regObj.test(documentText)) {
            var matches = documentText.match(regObj);
            result = matches[0].replace(/&nbsp;/g, "");
        }
    }
    //console.log("PriceParsed="+result);

    return result;
}


function jisu_removeTags(elem) {
    return elem.replace(/<(?:.|\n)*?>/gm, "")
}

function jisudiv_close() {
    var jisuMain = document.getElementById(JISU_MAIN_ELEM_ID);
    jisu_removeChildNodes(jisuMain);
    jisuMain.parentNode.removeChild(jisuMain);


}

function jisu_correctImage(image) {
    var imgsrc = image.src, width = image.width, height = image.height;

    if (image.getAttribute('src') === "undefined") return false;


    if (imgsrc.indexOf(JISU_MAIN_DOMAIN) > -1) return false;
    if (imgsrc.indexOf("javascript:") > -1) return false;
    if (image.getAttribute("nograb")) return false;
    if (imgsrc.indexOf("http") == -1) return false;
    if (imgsrc.toString().toLowerCase().indexOf("loading") > -1) return false;
    if (width < 80) return false;
    if (height < 80) return false;
    if (width / height > 2.5 || width / height < .5) return false;

    return true;
}

function jisu_linkCSS() {
    var a = document.createElement("link");
    a.setAttribute("rel", "stylesheet");
    a.setAttribute("type", "text/css");
    a.setAttribute("href", "http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css");
    (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(a);


    /*
     a = document.createElement("link");
     a.setAttribute("rel", "stylesheet");
     a.setAttribute("type", "text/css");
     a.setAttribute("href", JISU_MAIN_WEB_URL + "/css/style.css");
     (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(a);

    a = document.createElement("link");
    a.setAttribute("rel", "stylesheet");
    a.setAttribute("type", "text/css");
    a.setAttribute("href", "http://fonts.googleapis.com/css?family=Montserrat|Open+Sans:400,600,700");
    (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(a);
    */

    a = document.createElement("link");
    a.setAttribute("rel", "stylesheet");
    a.setAttribute("type", "text/css");
    a.setAttribute("href", "//fast.fonts.com/cssapi/01a79bb3-b904-48b1-9719-448e8f3e164f.css");
    (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(a);


    a = document.createElement("link");
    a.setAttribute("rel", "stylesheet");
    a.setAttribute("type", "text/css");
    a.setAttribute("href", JISU_MAIN_WEB_URL + "/css/tool.css");
    (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(a);

    /*
     a = document.createElement("link");
     a.setAttribute("rel", "stylesheet");
     a.setAttribute("type", "text/css");
     (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(a);
     */


}


jisu_initialize();
//jisu_linkCSS();
//jisu_createmainScript();
//jisu_loadAll();
